﻿using DevExpress.XtraEditors;
using System;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace BW.Mes.WinForms.BasicData
{
    public partial class UpdateCustomerForm : DevExpress.XtraEditors.XtraForm
    {
        private CustomerForm.CustomerModel _model;
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _apiBaseUrl = "https://localhost:7274";
        public UpdateCustomerForm(CustomerForm.CustomerModel model)
        {
            InitializeComponent();
            _model = model;
            // 反填
            textEditCode.Text = model.CustomerCode;
            textEditName.Text = model.CustomerName;
            textEditAbbreviation.Text = model.Abbreviation;
            textEditPhone.Text = model.Phone;
            textEditAddress.Text = model.Address;
            textEditUSCC.Text = model.USCC;
            textEditMsg.Text = model.CustomerMsg;
        }
        private async void btnOK_Click(object sender, EventArgs e)
        {
            var model = new
            {
                Id = _model.Id,
                CustomerCode = textEditCode.Text,
                CustomerName = textEditName.Text,
                Abbreviation = textEditAbbreviation.Text,
                Phone = textEditPhone.Text,
                Address = textEditAddress.Text,
                USCC = textEditUSCC.Text,
                CustomerMsg = textEditMsg.Text,
                UpdatedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"),
                UpdatedBy = "wyj",
                CreatedBy = _model.CreatedBy,
                CreatedAt = _model.CreatedAt
            };
            string jsonData = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            var response = await _httpClient.PutAsync($"{_apiBaseUrl}/api/Customer/UpdateCustomer", content);
            if (response.IsSuccessStatusCode)
            {
                XtraMessageBox.Show("修改成功！");
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                var errorMsg = await response.Content.ReadAsStringAsync();
                XtraMessageBox.Show($"修改失败！\n状态码: {response.StatusCode}\n内容: {errorMsg}");
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void UpdateCustomerForm_Load(object sender, EventArgs e)
        {

        }
    }
}